package com.iqismart.shorturl.schedule;

import com.iqismart.shorturl.cache.UrlCountCache;
import com.iqismart.shorturl.service.LogService;
import com.iqismart.shorturl.service.UrlService;
import com.iqismart.shorturl.vo.EaddRequest;
import com.iqismart.shorturl.vo.EaddResponse;
import com.iqismart.shorturl.vo.LogRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 随机的生成短链 并随机访问
 * @Auther sty
 * @createTime 2019-10-24 10:22
 */
@Component
public class  UrlSchedule {

    @Autowired
    private UrlService urlService;

    @Autowired
    private LogService logService;

    private static List<String> urls = new ArrayList<>();

    static {
        urls.add("https://www.aliyun.com/1111/2019/group-buying-share?ptCode=FE6BDB26A594E5EE02E98D708EFE2DB1647C88CF896EF535&userCode=4l9e98mw&share_source=copy_link");
        urls.add("https://cloud.tencent.com/act/double11/reserve?spread_hash_key=dfdrie");
        urls.add("http://h5.renmaitong.com/");
        urls.add("https://a.app.qq.com/o/simple.jsp?pkgname=com.bizsocialnet&channel=0002160650432d595942&fromcase=60001");
    }

    /**
     * 每秒一次
     * 随机生成几个短链 每个短链有10%概率被访问
     */
    @Scheduled(fixedDelay = 300)
    public void run(){
        start();
    }

    private void start() {
        if(!isRun()){
           return;
        }
        int random =Double.valueOf(Math.random()*10 + 1).intValue();

        random = 1;
        for (int i = 0; i <= random; i++) {
            final EaddRequest request = new EaddRequest();
            request.setLongurl(urls.get(i%urls.size()));
            final EaddResponse eadd = urlService.eadd(request);
            if(isGet()){
                final LogRequest logRequest = new LogRequest();
                logRequest.setUrlId(eadd.getId());
                logService.add(logRequest);
                UrlCountCache.todayGet.incrementAndGet();
            }
        }
    }

    public static boolean isRun(){
        int random =Double.valueOf(Math.random()*1000 + 1).intValue();
        if(random < 300 ){
            return true;
        }
        return false;
    }

    public static boolean isGet(){
        int random =Double.valueOf(Math.random()*1000 + 1).intValue();
        if(random < 50 ){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(isGet());
        }
    }
}
